package com.wzy.server.config.security;

import com.wzy.server.config.CustomFilter;
import com.wzy.server.config.CustomUrlDecisionManager;
import com.wzy.server.pojo.Admin;
import com.wzy.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {//自定义Security策略


	@Autowired
	private IAdminService adminService;
	@Autowired
	private RestAuthenticationEntryPoint restAuthenticationEntryPoint;//注入自定义未登录返回结果
	@Autowired
	private RestfulAccessDeniedHandler restfulAccessDeniedHandler;//注入自定义未授权返回结果
	@Autowired
	private CustomUrlDecisionManager customUrlDecisionManager;
	@Autowired
	private CustomFilter customFilter;


//放行静态资源
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers(//路径
				"/login",
				"/logout",
				"/css/**",
				"/js/**",
				"/index.html",
				"/img/**",
				"/fonts/**",
				"/favicon.ico",  //图标
				"/doc.html",    //swagger2
				"/webjars/**",
				"/swagger-resources/**",
				"/v2/api-docs/**",
				"/ws/**",  //聊天websocket
				"/captcha"); //验证码
	}

//	认证（实现我自己重写的userdetailservice方法）
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//		                            获取用户名                              加密密码
		auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
	}

//授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//使用JWT，不需要csrf，关闭之后可防止注销404
		http.csrf().disable()//关闭csrf功能：跨站请求防伪，默认只能通过post方式提交logout请求
				//基于token，不需要session
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()//表示继续向下配置
				.authorizeRequests()//认证请求
				//允许登录访问
				.antMatchers("/login","/logout").permitAll()//所有人可以访问
				.antMatchers("/employee/**").permitAll()
				//除上面外，所有请求都要求认证拦截
				.anyRequest().authenticated()
				//动态权限配置
				.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
					@Override
					public <O extends FilterSecurityInterceptor> O postProcess(O o) {
						o.setAccessDecisionManager(customUrlDecisionManager);
						o.setSecurityMetadataSource(customFilter);
						return o;
					}
				})
				.and()
				//禁用缓存
				.headers().cacheControl();
		//添加jwt 登录授权过滤器
		http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
		//添加自定义未授权和未登录结果返回
		http.exceptionHandling()
				.accessDeniedHandler(restfulAccessDeniedHandler)
				.authenticationEntryPoint(restAuthenticationEntryPoint);
	}

//	创建密码加密对象  bcrypt加密方法
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

//	重写userdetailservice方法
	@Override
	@Bean
	public UserDetailsService userDetailsService() {
		//获取登录用户信息（根据用户名获取用户的方法）
		return username -> {
			Admin admin = adminService.getAdminByUserName(username);
			if (null != admin) {
//				添加角色信息
				admin.setRoles(adminService.getRoles(admin.getId()));
				return admin;
			}
			throw new UsernameNotFoundException("用户名或密码不正确");
		};
	}

//	登陆授权引入
	@Bean
	public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
		return new JwtAuthenticationTokenFilter();
	}
}